﻿using UnityEditor;
using UnityEngine;
using System.Collections;

[CustomEditor(typeof(PUEXForceAffector))]
public class PUEXForceAffectorEditor : Editor {
	
	public void OnSceneGUI ()
	{
		var affector = target as PUEXForceAffector;
		if (!affector.enabled)
			return;
		
		Matrix4x4 defaultMatrix = Handles.matrix;
		if (affector.inWorldSpace) {
			Handles.matrix = Matrix4x4.identity;
		} else {
			Handles.matrix = affector.transform.parent.transform.localToWorldMatrix;
		}
		
		Quaternion quat = Quaternion.LookRotation(affector.force.normalized);

		if (Tools.current == Tool.Move) {
			Vector3 value = Handles.PositionHandle (affector.center, Quaternion.identity);

			if (GUI.changed) {
				Undo.RecordObject(affector, "PUEXForceFieldAffector Modify");
				affector.center = value;
				EditorUtility.SetDirty(affector);
			}
		} else if (Tools.current == Tool.Rotate) {
			quat = Handles.RotationHandle (quat, affector.center);
			Vector3 value = quat * (Vector3.forward * affector.force.magnitude);

			if (GUI.changed) {
				Undo.RecordObject(affector, "PUEXForceFieldAffector Modify");
				affector.force = value;
				EditorUtility.SetDirty(affector);
			}
		} else if (Tools.current == Tool.Scale) {
			float value = Handles.ScaleSlider(affector.force.magnitude, 
			                    affector.center, 
			                    affector.force.normalized, 
			                    Quaternion.identity, 
			                    HandleUtility.GetHandleSize(affector.center),
			                    1f);

			if (GUI.changed) {
				Undo.RecordObject(affector, "PUEXForceFieldAffector Modify");
				affector.force = affector.force.normalized * value;
				EditorUtility.SetDirty(affector);
			}
		}

		Handles.DrawLine (affector.center, affector.center + affector.force);
		Handles.ConeCap(0, affector.center + affector.force, quat, HandleUtility.GetHandleSize(affector.center) * 0.2f);
		
		Handles.matrix = defaultMatrix;
	}
	
}
